package com.icesoft.core.common.helper;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.icesoft.core.common.util.JsonUtil;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 接收http请求的json数据
 *
 * @author XHH
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class Resp<T> implements Serializable {

    private int code = RespCode.SUCCESS;
    private String msg = "成功";
    private T data;

    public Resp() {
        super();
    }

    /**
     * 请求错误回应
     */
    public Resp(String errMsg) {
        super();
        this.setMsg(errMsg + "");
        this.setCode(RespCode.FAIL);
    }

    /**
     * 请求异常回应
     */
    public Resp(Throwable e) {
        super();
        this.setMsg(e.getMessage() + "");
        this.setCode(RespCode.FAIL);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Resp<T> data(T data) {
        this.data = data;
        return this;
    }

    public Resp<T> msg(String msg) {
        this.msg = msg;
        return this;
    }

    public Resp<T> code(int code) {
        this.code = code;
        return this;
    }

    public static Resp success() {
        return new Resp<>();
    }

    public static <T> Resp<T> success(T data) {
        return new Resp<T>().data(data);
    }

    public static <T> Resp<T> success(T data, String msg) {
        return new Resp<T>().data(data).msg(msg + "");
    }

    public static <T> Resp<T> error(String msg) {
        return new Resp<>(msg);
    }
    public static <T> Resp<T> error(Exception e) {
        return error(e.getMessage());
    }
    public static <T> Resp<T> error(int code) {
        return error(code, "error");
    }

    public static <T> Resp<T> error(int code, String msg) {
        Resp<T> resp = new Resp<>();
        resp.setCode(code);
        resp.setMsg(msg);
        return resp;
    }

    @JsonIgnore
    public boolean isSuccess() {
        return code == RespCode.SUCCESS;
    }

    @Override
    public String toString() {
        return "{\"msg\":\"" + msg + "\",\"code\":" + code + ",\"data\":\"" + data + "\"}";
    }

    public Map<String, Object> toMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("msg", msg);
        map.put("data", data);
        return map;
    }

    public String toJson() {
        return JsonUtil.toJson(this);
    }
}
